/* 2014/7/28 */
package cosmos.media;

import java.util.Arrays;

public class ID3v2Header {

	public static final int TOTAL_LENGTH = 10;
	public static final int HEADER_LENGTH = 3;
	public static final int SIZE_LENGTH = 4;
	
	private static final byte[] AVAILABLE_HEADER = 
			new byte[] {(byte)'I', (byte)'D', (byte)'3'};
	
	private byte[] header;
	
	private byte ver;
	
	private byte revision;
	
	private byte flag;
	
	private byte[] size;

	public ID3v2Header() {
		header = new byte[HEADER_LENGTH];
		size = new byte[SIZE_LENGTH];
	}

	/**
	 * Loads ID3V2 tag header information from a byte array.
	 * @param bytes - Bytes of ID3V2 tag header, which are extracted from head of file.
	 */
	public void load(byte[] bytes) {
		int i;
        int j;
        int position = 0;
        int currentIndex = 0;

        // Extracts header.
        for (i = currentIndex, j = 0; i < currentIndex + HEADER_LENGTH;
            i++, j++)
        {
            header[j] = bytes[i];
            position++;
        }
        currentIndex = position;

        // Extracts ver bit.
        ver = bytes[++position];

        // Extracts revision bit.
        revision = bytes[++position];

        // Extracts flag bit.
        flag = bytes[++position];

        // Extracts size.
        for (i = currentIndex, j = 0; i < currentIndex + SIZE_LENGTH;
            i++, j++)
        {
            size[j] = bytes[i];
            position++;
        }
        currentIndex = position;
	}
	
	public boolean isAvailable() {
		return Arrays.equals(header, AVAILABLE_HEADER);
	}
	
	public byte[] getHeader() {
		return header;
	}
	
	public byte getVer() {
		return ver;
	}

	public void setVer(byte ver) {
		this.ver = ver;
	}

	public byte getRevision() {
		return revision;
	}

	public void setRevision(byte revision) {
		this.revision = revision;
	}

	public byte getFlag() {
		return flag;
	}

	public void setFlag(byte flag) {
		this.flag = flag;
	}

	public byte[] getSize() {
		return size;
	}

	public void setSize(byte[] size) {
		this.size = size;
	}
	
	public int getAllFrameSize() {
		int allFrameSize
        	= (size[0] & 0x7F) * 0x200000
        	+ (size[1] & 0x7F) * 0x400
        	+ (size[2] & 0x7F) * 0x80
        	+ (size[3] & 0x7F);
		return allFrameSize;
	}
}
